# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(scatterplot3d)
library(optparse)
library(tidyverse)
library(magrittr)
library(extrafont)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "", type = "character", help = "sample color file"),
  make_option("--pc", default = "", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"),recursive =F, prompt = F)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config_json.R"))
baseFamily <- fontFamily

if (!file.exists(opt$sc)) {
  file.copy("Class_Color.txt", opt$sc)
}

sampleColDf <- tibble(ClassNote = plotConfigJson$color$groups, col = plotConfigJson$color$colors)

parent <- "./"
createWhenNoExist(parent)
modelFileName <- paste0(parent, "/PLSDA_R2X_R2Y_Q2.csv")
dataFileName <- paste0(parent, "/PLSDA_Score.csv")
fileName <- paste0(parent, "/PLSDA_Score_3D.pdf")

pdf(fileName, width = width, height = height)

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

sampleInfo

xPc <- x %>%
  str_c("C", .)
yPc <- y %>%
  str_c("C", .)
zPc <- z %>%
  str_c("C", .)

plotData <- read_csv(dataFileName) %>%
  rename(SampleID = X1) %>%
  select(c("SampleID", xPc, yPc, zPc)) %>%
  set_colnames(c("SampleID", "xPc", "yPc", "zPc")) %>%
  left_join(sampleInfo, by = c("SampleID")) %>%
  left_join(sampleColDf, by = c("ClassNote"))

head(plotData)
modelDf <- read.csv(modelFileName, header = T, row.names = 1)

impoPc1 <- modelDf[xPc, "R2X"]
impoPc1 <- round(impoPc1 * 100, 2)
impoPc2 <- modelDf[yPc, "R2X"]
impoPc2 <- round(impoPc2 * 100, 2)
impoPc3 <- modelDf[zPc, "R2X"]
impoPc3 <- round(impoPc3 * 100, 2)


opar <- par(no.readonly = TRUE)
par(family = baseFamily)

main <- if (!is.na(mainTitle)) {
  mainTitle
} else ""

scatterplot3d(plotData$xPc, plotData$yPc, plotData$zPc, color = plotData$col, main = main, pch = 20, col.axis = "grey",
              mar = c(5, 3, 1, 3) + 0.1, cex.symbols = 6, xlab = str_c("Component ", x, " (", impoPc1, "%)"),
              ylab = str_c("Component ", y, " (", impoPc2, "%)"), zlab = str_c("Component ", z, " (", impoPc3, "%)"),
              angle = 60, cex.lab = 2, cex.axis = 1.5)

par(opar)

dev.off()